package com.lmt.common.util;

import com.lmt.entity.UserInfo;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

public class PasswordUtil {

    public static final String PASSWORD_ALGORITHM_NAME = "MD5";
    public static final Integer PASSWORD_HASH_ITERATIONS = 2;

    /**
     * md5 设置盐和加密密码
     * 散列算法是：md5(md5(密码+username+randomNumber))
     * @param userInfo 用户信息
     */
    public static void setSaltAndEncodedPassword(UserInfo userInfo) {
        String randomNumber = new SecureRandomNumberGenerator().nextBytes().toHex();
        String salt = userInfo.getUsername() + randomNumber;
        userInfo.setSalt(salt);
        SimpleHash hash = new SimpleHash(
                PasswordUtil.PASSWORD_ALGORITHM_NAME,
                userInfo.getPassword(),
                salt,
                PasswordUtil.PASSWORD_HASH_ITERATIONS);
        userInfo.setPassword(hash.toHex());
    }
}
